package com.youkeyi.ddy.cloud.basic.crm.type.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youkeyi.ddy.cloud.basic.crm.type.entity.SysCustomerType;
import com.youkeyi.ddy.cloud.basic.crm.type.service.SysCustomerTypeService;
import com.youkeyi.ddy.cloud.common.api.basic.crm.type.CrmCustomerTypeCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.crm.type.dto.CrmCustomerTypeListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.crm.type.dto.CrmCustomerTypeListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.crm.type.param.CrmCustomerTypeCreateCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.crm.type.param.CrmCustomerTypeDeleteCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.crm.type.param.CrmCustomerTypeQueryCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.crm.type.param.CrmCustomerTypeUpdateCloudParam;
import com.youkeyi.ddy.cloud.common.constant.YoukeyiDdyCloudBasicPublicConstant;
import com.youkeyi.ddy.cloud.common.enums.ResponseCodeEnum;
import com.youkeyi.ddy.cloud.common.response.ResponseContent;
import com.youkeyi.ddy.cloud.common.utils.SimpleUUidUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户类型表 前端控制器
 * </p>
 *
 * @author xiawang.liu
 * @since 2024-04-11
 */
@Service
public class SysCustomerTypeController implements CrmCustomerTypeCloudService {
    
    @Autowired
    private SysCustomerTypeService sysCustomerTypeService;

    @Override
    public CrmCustomerTypeListCloudDto query(CrmCustomerTypeQueryCloudParam param) {
        CrmCustomerTypeListCloudDto dto = new CrmCustomerTypeListCloudDto();
        if (null == param) {
            dto.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return dto;
        }

        if (CollectionUtils.isNotEmpty(param.getCustomerTypePrimaryKeys())) {
            param.getCustomerTypePrimaryKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getCorpKeys())) {
            param.getCorpKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getCodes())) {
            param.getCodes().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getNames())) {
            param.getNames().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getParentKeys())) {
            param.getParentKeys().removeAll(Collections.singleton(null));
        }

        QueryWrapper<SysCustomerType> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .in(CollectionUtils.isNotEmpty(param.getCustomerTypePrimaryKeys()), SysCustomerType::getPrimaryKey, param.getCustomerTypePrimaryKeys())
                .in(CollectionUtils.isNotEmpty(param.getCorpKeys()), SysCustomerType::getCorpKey, param.getCorpKeys())
                .in(CollectionUtils.isNotEmpty(param.getNames()), SysCustomerType::getName, param.getNames())
                .like(StringUtils.isNotBlank(param.getNameFuzzy()), SysCustomerType::getName, param.getNameFuzzy())
                .in(CollectionUtils.isNotEmpty(param.getCodes()), SysCustomerType::getCode, param.getCodes())
                .like(StringUtils.isNotBlank(param.getCodeFuzzy()), SysCustomerType::getCode, param.getCodeFuzzy())
                .in(CollectionUtils.isNotEmpty(param.getParentKeys()), SysCustomerType::getParentKey, param.getParentKeys())
                .eq(null != param.getLevel(), SysCustomerType::getLevel, param.getLevel())
                .ne(SysCustomerType::getIsDeleted, YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_YES.value())
        ;

        Page<SysCustomerType> page = new Page<>();
        if (null != param.getCurrentPage() && null != param.getPageSize()) {
            page.setCurrent(param.getCurrentPage());
            page.setSize(param.getPageSize());
        } else {
            page.setCurrent(1);
            page.setSize(99999999);
        }
        Page<SysCustomerType> customerTypeList = sysCustomerTypeService.page(page, wrapper);
        if (CollectionUtils.isNotEmpty(customerTypeList.getRecords())) {
            dto.setTotal(customerTypeList.getTotal());

            Map<String, String> parentKeyMap = new HashMap<>();
            if (param.getNeedParent()) {
                List<String> parentKeys = customerTypeList.getRecords().stream().map(SysCustomerType::getParentKey).collect(Collectors.toList());
                QueryWrapper<SysCustomerType>queryParentWrapper = new QueryWrapper<>();
                queryParentWrapper.lambda()
                        .in(SysCustomerType::getPrimaryKey, parentKeys)
                ;
                List<SysCustomerType> customerTypes = sysCustomerTypeService.list(queryParentWrapper);
                if (CollectionUtils.isNotEmpty(customerTypes)) {
                    parentKeyMap.putAll(customerTypes.stream().collect(Collectors.toMap(SysCustomerType::getPrimaryKey, SysCustomerType::getName)));
                }
            }

            List<CrmCustomerTypeListItemCloudDto> items = new ArrayList<>();
            customerTypeList.getRecords().forEach(customerType -> {
                CrmCustomerTypeListItemCloudDto item = new CrmCustomerTypeListItemCloudDto();
                item.setCustomerTypePrimaryKey(customerType.getPrimaryKey());
                item.setCorpKey(customerType.getCorpKey());
                item.setName(customerType.getName());
                item.setCode(customerType.getCode());
                item.setLevel(customerType.getLevel());
                item.setParentKey(customerType.getParentKey());
                item.setParentName(parentKeyMap.get(customerType.getParentKey()));
                item.setPath(customerType.getPath());
                item.setDesc(customerType.getDesc());
                item.setIsDeleted(customerType.getIsDeleted());
                item.setIsDeletedName(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO.getName(item.getIsDeleted()));
                item.setCreateTime(customerType.getCreateTime() != null ? customerType.getCreateTime().getTime() : null);
                item.setCreateUserKey(customerType.getCreateUserKey());
                item.setCreateUserName(customerType.getCreateUserName());
                item.setUpdateTime(customerType.getUpdateTime() != null ? customerType.getUpdateTime().getTime() : null);
                item.setUpdateUserKey(customerType.getUpdateUserKey());
                item.setUpdateUserName(customerType.getUpdateUserName());
                items.add(item);
            });
            dto.setRows(items);
        }
        dto.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        return dto;
    }

    @Override
    public ResponseContent create(CrmCustomerTypeCreateCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param
                || StringUtils.isBlank(param.getName())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }
        SysCustomerType customerType = new SysCustomerType();
        customerType.setPrimaryKey(SimpleUUidUtils.getUuid());
        customerType.setCorpKey(param.getCorpKey());
        customerType.setName(param.getName());
        customerType.setCode(StringUtils.isNotBlank(param.getCode()) ? param.getCode() : String.format("CUSTOMER-TYPE-%s", System.currentTimeMillis()));
        customerType.setDesc(param.getDesc());
        customerType.setIsDeleted(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_NO.value());
        customerType.setCreateUserKey(param.getCreateUserKey());
        customerType.setCreateUserName(param.getCreateUserName());
        customerType.setCreateTime(new Date());

        // 构造父级数据
        customerType.setLevel(0);
        customerType.setParentKey("");
        customerType.setPath(String.format("|%s|", customerType.getPrimaryKey()));
        if (StringUtils.isNotBlank(param.getParentKey())) {
            QueryWrapper<SysCustomerType> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SysCustomerType::getPrimaryKey, param.getParentKey());
            SysCustomerType parentCustomerType = sysCustomerTypeService.getOne(queryWrapper);
            if (null != parentCustomerType && StringUtils.isNotBlank(parentCustomerType.getPrimaryKey())) {
                customerType.setLevel(parentCustomerType.getLevel() + 1);
                customerType.setParentKey(parentCustomerType.getPrimaryKey());
                customerType.setPath(String.format("%s|", parentCustomerType.getPath()));
            }
        }

        boolean save = sysCustomerTypeService.save(customerType);
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
            return rc;
        }
        rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        rc.setKey(customerType.getPrimaryKey());
        return rc;
    }

    @Override
    public ResponseContent update(CrmCustomerTypeUpdateCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param || StringUtils.isBlank(param.getCustomerTypePrimaryKey())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }


        QueryWrapper<SysCustomerType> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysCustomerType::getPrimaryKey, param.getCustomerTypePrimaryKey());
        SysCustomerType myselfCustomerType = sysCustomerTypeService.getOne(queryWrapper);
        if (null == myselfCustomerType || StringUtils.isBlank(myselfCustomerType.getPrimaryKey())) {
            rc.setErrorMessage(ResponseCodeEnum.UNKNOWN_ERROR.getMessage());
            return rc;
        }


        UpdateWrapper<SysCustomerType> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .eq(SysCustomerType::getPrimaryKey, param.getCustomerTypePrimaryKey());
        SysCustomerType customerType = new SysCustomerType();
        customerType.setPrimaryKey(param.getCustomerTypePrimaryKey());
        customerType.setName(param.getName());
        customerType.setCode(param.getCode());
        customerType.setDesc(param.getDesc());
        customerType.setUpdateUserKey(param.getUpdateUserKey());
        customerType.setUpdateUserName(param.getUpdateUserName());
        customerType.setUpdateTime(new Date());

        if (!myselfCustomerType.getParentKey().equals(param.getParentKey())) {
            // 构造父级数据
            customerType.setLevel(0);
            customerType.setParentKey("");
            customerType.setPath(String.format("|%s|", customerType.getPrimaryKey()));
            if (StringUtils.isNotBlank(param.getParentKey())) {
                QueryWrapper<SysCustomerType> queryParentWrapper = new QueryWrapper<>();
                queryParentWrapper.lambda().eq(SysCustomerType::getParentKey, param.getParentKey());
                SysCustomerType parentCustomerType = sysCustomerTypeService.getOne(queryParentWrapper);
                if (null != parentCustomerType && StringUtils.isNotBlank(parentCustomerType.getPrimaryKey())) {
                    customerType.setLevel(parentCustomerType.getLevel() + 1);
                    customerType.setParentKey(parentCustomerType.getPrimaryKey());
                    customerType.setPath(String.format("%s|", parentCustomerType.getPath()));
                }
            }
        }

        boolean save = sysCustomerTypeService.update(customerType, wrapper);
        rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
            return rc;
        }
        return rc;
    }

    @Override
    public ResponseContent delete(CrmCustomerTypeDeleteCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param || CollectionUtils.isEmpty(param.getCustomerTypePrimaryKeys())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }
        UpdateWrapper<SysCustomerType> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .in(SysCustomerType::getPrimaryKey, param.getCustomerTypePrimaryKeys());

        SysCustomerType customerType = new SysCustomerType();
        customerType.setIsDeleted(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_YES.value());
        customerType.setUpdateUserKey(param.getUpdateUserKey());
        customerType.setUpdateUserName(param.getUpdateUserName());
        customerType.setUpdateTime(new Date());
        boolean save = sysCustomerTypeService.update(customerType, wrapper);
        rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
        }
        return rc;
    }
}
